﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace QFramework
{
    public interface IItemKitSaverAndLoader
    {
        void Save(Dictionary<string,SlotGroup> slotGroups);
        
        void Load(Dictionary<string,SlotGroup> slotGroups);
        
        void clear();
    }
    
    /// <summary>
    /// 默认的加载&存档器
    /// </summary>
    public class DefaultItemKitSaverAndLoader : IItemKitSaverAndLoader
    {
        [Serializable]
        public class SaveData
        {
            public string Key;
            public List<SlotData> Slots = new List<SlotData>();
        }

        [Serializable]
        public class SlotData
        {
            public string ItemKey;
            public int Count;
        }
        
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="slotGroups"></param>
        public void Save(Dictionary<string, SlotGroup> slotGroups)
        {
            // 避免动态生成SlotGroup导致PlayerPrefs中没有数据，所以先保存所有SlotGroup的Key
            var keyString = string.Join("@@", slotGroups.Keys.ToList());
            PlayerPrefs.SetString("slot_group_keys",keyString);
            
            // 遍历所有格子数据，进行保存
            foreach (var slotGroup in slotGroups.Values)
            {
                var slotGroupSaveData = new SaveData()
                {
                    Key = slotGroup.Key,
                    Slots = slotGroup.Slots.Select(slot => new SlotData()
                    {
                        ItemKey = slot.Item != null ? slot.Item.GetKey : null,
                        Count = slot.Count,
                    }).ToList()
			        
                };
		        
                var json = JsonUtility.ToJson(slotGroupSaveData);
                json.LogInfo();
                PlayerPrefs.SetString("slot_group_"+slotGroup.Key,json);
                Debug.Log("保存完毕");
            }
        }
        
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="slotGroups"></param>
        public void Load(Dictionary<string, SlotGroup> slotGroups)
        {
            // 读取所有SlotGroup的Key
            var keyString = PlayerPrefs.GetString("slot_group_keys", String.Empty);
            var keys = keyString.Split("@@").ToList();
            
            // 遍历所有SlotGroup，如果存在则加载数据，如果不存在则证明这个是动态创建的key，需要创建这个SlotGroup
            foreach (var key in keys)
            {
                SlotGroup slotGroup = null;
                if (slotGroups.ContainsKey(key))
                {
                    slotGroup = slotGroups[key];
                }
                else
                {
                    slotGroup = ItemKit.CreateSlotGroup(key);
                }
                
                var json = PlayerPrefs.GetString("slot_group_" + slotGroup.Key,String.Empty);
                if (json.IsNullOrEmpty())
                {
			        Debug.Log("加载失败！没有任何存档数据！");
                }
                else
                {
                    // 把json转化成SlotGroupSaveData
                    var saveData = JsonUtility.FromJson<SaveData>(json);
                    // 遍历SlotGroupSaveData，设置SlotGroup
                    for (int i = 0; i < saveData.Slots.Count; i++)
                    {
                        var slotSaveData = saveData.Slots[i];
                        var item = slotSaveData.ItemKey.IsNullOrEmpty()?null:ItemKit.ItemByKey[slotSaveData.ItemKey];
                        // 如果存档中的slot数量大于SlotGroup中的数量，则需要创建新的Slot
                        if (i<slotGroup.Slots.Count)
                        {
                            slotGroup.Slots[i].Item = item;
                            slotGroup.Slots[i].Count = slotSaveData.Count;
                            slotGroup.Slots[i].Changed.Trigger();
                        }
                        else
                        {
                            slotGroup.CreateSlot(item, slotSaveData.Count);
                        }
                    }
                }
            }
            //
            // foreach (var slotGroup in slotGroups.Values)
            // {
            //     
            // }
        }

        /// <summary>
        /// 清除所有数据
        /// </summary>
        public void clear()
        {
            var keyString = PlayerPrefs.GetString("slot_group_keys", String.Empty);
            var keys = keyString.Split("@@").ToList();
            foreach (var key in keys)
            {
                PlayerPrefs.DeleteKey("slot_group_" + key);
            }
            PlayerPrefs.DeleteKey("slot_group_keys");
        }
    }
}